<?php
/**
 * 处理控制器
 */
namespace app\manage\controller\bonus;

use app\manage\controller\Base;

use app\common\query\Plugin;

class Handle extends Base
{
	private $params;
    public function __construct(){
        parent::__construct();
        // token验证
        if(false == Base::checkToken()){
            $this->error('token error!');
        }
        // 参数去token
        $params = input();
        unset($params['token']);
        $this->params = $params;
    }

	public function addConfig(){
		$params = $this->params;

		$bonus_name = $params['bonus_name'];
		$config_name = $params['config_name'];
		$config = $params['data'];

		if($config_name=='coin'){
			if(empty($config)){
				$this->error('货币配置错误');
			}
			$total = 0;
			$coinFlag = [];
			foreach($config as $value):
				$total += $value['config'];
				if(in_array($value['coin_id'],$coinFlag)){
					$this->error('货币类型不能重复');
				}else{
					$coinFlag[] = $value['coin_id'];
				}
			endforeach;
			if($total!=100){
				$this->error('货币配置比例总和必须等于100');
			}
		}

		$data = [
			'bonus_name' => $bonus_name,
			'config_name' => $config_name,
			'config_value' => serialize($config)
		];

		$model = model('bonus_config');

		$model -> saveOneData($data);

		// 更新缓存
		$CACHE = \app\common\cache\CacheData::getInstance('BonusConfig');
		$CACHE -> updateCache();

		$this->success('保存成功');

	}

	public function export(){
		$params = $this->params;

    	$where = parseWhere($params);
    	$model = model('bonus_config');
    	$datas = $model->getDatas($where,['id','bonus_name','effect_mid','reason_mid','coin_id','amount','remark','reason_time','create_time','status']);

    	$excelData = "记录编号\t奖金类型\t会员编号\t奖金来源\t货币类型\t金额\t说明\t产生时间\t结算时间\t状态\t\n";
    	foreach($datas as $value):
    		$excelData .= $value['id']."\t";
            $excelData .= $value['bonus_tag']."\t";
            $excelData .= $value['effect_mid']."\t";
            $excelData .= $value['reason_mid']."\t";
            $excelData .= $value['coin_name']."\t";
            $excelData .= $value['amount']."\t";
            $excelData .= $value['remark']."\t";
            $excelData .= $value['reason_date']."\t";
            $excelData .= $value['create_date']."\t";
            $excelData .= $value['status_remark']."\t";
			$excelData .= "\n";
    	endforeach;
    	$excelData = iconv('utf-8','gb2312',$excelData);

    	exportExcel(time().'.xls',$excelData);
	}

}